﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity.RSS_Feed;
using System.Net;
using System.IO;
using System.Xml;
using System.Diagnostics;
using Entity;

namespace DataAccess
{
    public class DouBanHelper
    {
        /// <summary>
        /// 通过 userID 查询用户
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public static XmlDocument GetPeopleXMLDocument(string ID)
        {
            if (string.IsNullOrEmpty(ID)) return null;
            string userUrl = @"http://api.douban.com/people/" + ID;
            
            // Create a request for the URL.         
            WebRequest request = WebRequest.Create(userUrl);
            HttpWebResponse response = null;
            Stream dataStream = null;
            XmlDocument peopleEntry = null;
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                // Get the response.
                response = (HttpWebResponse)request.GetResponse();

                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                peopleEntry = new XmlDocument();
                peopleEntry.Load(dataStream);
                return peopleEntry;
            }
            catch (WebException e)
            {
                throw;
            }
            finally
            {
                dataStream = null;
                response = null;
            }
        }

        
        /// <summary>
        /// 通过邮件地址查询 用户
        /// </summary>
        /// <param name="registerEmail">用户注册时 所用邮件地址</param>
        /// <returns></returns>
        public static XmlDocument QueryUserByEmail(string registerEmail)
        {
            if (string.IsNullOrEmpty(registerEmail)) return null;
            string queryUrl = @"http://api.douban.com/people?q=" + registerEmail + "&start-index=1&max-results=1";
            // Create a request for the URL.         
            WebRequest request = WebRequest.Create(queryUrl);
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = null;
            Stream dataStream = null;
            XmlDocument peopleEntry = null;

            try
            {
                // Get the response.
                response = (HttpWebResponse)request.GetResponse();

                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                peopleEntry = new XmlDocument();
                peopleEntry.Load(dataStream);
            }
            catch (WebException e)
            {
                throw;
            }
            finally
            {
                dataStream = null;
                response = null;
            }
            return peopleEntry;
        }

        /// <summary>
        /// Construct people object from query result xml document
        /// </summary>
        /// <param name="peopleXml"></param>
        /// <returns></returns>
        public static People GetPeopleFromXml(XmlDocument peopleXml)
        {
            if (peopleXml == null) return null;
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(peopleXml.NameTable);
            nsmgr.AddNamespace("atom", @"http://www.w3.org/2005/Atom");
            nsmgr.AddNamespace("db", @"http://www.douban.com/xmlns/");
            nsmgr.AddNamespace("gd", @"http://schemas.google.com/g/2005");
            nsmgr.AddNamespace("opensearch", @"http://a9.com/-/spec/opensearchrss/1.0/");

            string uid;
            string location;
            string title;
            string content;
            string selfURL;
            string homePage;
            string iconUrl;
            People doubanPeople = null;
            try
            {
                XmlNode feedNode = peopleXml.SelectSingleNode(@"/atom:feed/atom:entry", nsmgr);
                XmlNode locationNode = feedNode.SelectSingleNode(@"//db:location", nsmgr);
                XmlNode uidNode = feedNode.SelectSingleNode(@"//db:uid", nsmgr);
                Debug.Assert(uidNode != null, "未取到用户ID");
                XmlNode titleNode = feedNode.SelectSingleNode(@"//atom:title", nsmgr);
                XmlNode contentNode = feedNode.SelectSingleNode(@"//atom:content", nsmgr);
                XmlNode selfURLNode = feedNode.SelectSingleNode(@"//atom:link[@rel='self']", nsmgr);
                XmlNode homePageNode = feedNode.SelectSingleNode(@"//atom:link[@rel='homepage']", nsmgr);
                XmlNode iconNode = feedNode.SelectSingleNode(@"//atom:link[@rel='icon']", nsmgr);

                if (uidNode == null)
                {
                    uid = null;
                }
                else
                {
                    uid = uidNode.InnerText;
                }

                if (locationNode == null) location = null;
                else location = locationNode.InnerText;

                if (titleNode == null) title = null;
                else title = titleNode.InnerText;

                if (contentNode == null) content = null;
                else content = contentNode.InnerText;

                if (selfURLNode == null) selfURL = null;
                else selfURL = selfURLNode.Attributes["href"].Value;

                if (homePageNode == null) homePage = null;
                else homePage = homePageNode.Attributes["href"].Value;

                if (iconNode == null) iconUrl = null;
                else iconUrl = iconNode.Attributes["href"].Value;

                doubanPeople = new People(uid,
                location,
                title,
                content,
                selfURL,
                homePage,
                iconUrl);
            }
            catch (NullReferenceException ex)
            {
                //如果是空引用的异常那么 我们不处理它，意思是实参参数中没有包含有效的数据。
            }
            
            return doubanPeople;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="eventXml"></param>
        /// <returns></returns>
        public static List<OneCityEvent> GetOneCityEventFromXML(XmlDocument eventsFeed)
        {
            if (eventsFeed == null) return null;    //检查参数合法性

            List<OneCityEvent> events = new List<OneCityEvent>();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(eventsFeed.NameTable);
            nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
            nsmgr.AddNamespace("db", "http://www.douban.com/xmlns/");
            nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005");
            nsmgr.AddNamespace("opensearch", "http://a9.com/-/spec/opensearchrss/1.0/");

            XmlNodeList eventEntries = eventsFeed.SelectNodes(@"//atom:entry", nsmgr);
            foreach (XmlNode eventEntry in eventEntries)
            {
                XmlNode idNode = eventEntry.SelectSingleNode(@"./atom:id", nsmgr);
                XmlNode titleNode = eventEntry.SelectSingleNode(@"./atom:title", nsmgr);
                XmlNode whenNode = eventEntry.SelectSingleNode(@"./gd:when", nsmgr);
                XmlNode whereNode = eventEntry.SelectSingleNode(@"./gd:where", nsmgr);

                OneCityEvent userEvent = new OneCityEvent(idNode.InnerText);
                userEvent.Title = titleNode.InnerText;
                userEvent.StartTime = DateTime.Parse(whenNode.Attributes["startTime"].Value);
                userEvent.EndTime = DateTime.Parse(whenNode.Attributes["endTime"].Value);
                userEvent.Where = whereNode.Attributes["valueString"].Value;

                events.Add(userEvent);
            }

            return events;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="newsFeed"></param>
        /// <returns></returns>
        public static List<UserNews> GetUserNewsFromXML(XmlDocument newsFeed)
        {
            if (newsFeed == null) return null;  //检查参数合法性

            List<UserNews> userNews = new List<UserNews>();

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(newsFeed.NameTable);
            nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
            nsmgr.AddNamespace("db", "http://www.douban.com/xmlns/");
            nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005");
            nsmgr.AddNamespace("opensearch", "http://a9.com/-/spec/opensearchrss/1.0/");
            XmlNodeList newsEntries = newsFeed.SelectNodes(@"//atom:entry", nsmgr);

            //iterate the node list, construct the news entry
            foreach (XmlNode newsNode in newsEntries)
            {
                XmlNode idNode = newsNode.SelectSingleNode(@"./atom:id", nsmgr);
                XmlNode titleNode = newsNode.SelectSingleNode(@"./atom:title", nsmgr);
                XmlNode publishedNode = newsNode.SelectSingleNode(@"./atom:published", nsmgr);
                // fetch three attibutes for now.
                string id = idNode.InnerText;
                UserNews newsEntry = new UserNews(id);
                newsEntry.Title = titleNode.InnerText;
                newsEntry.Published = DateTime.Parse(publishedNode.InnerText);
                userNews.Add(newsEntry);
            }
            
            return userNews;
        }

        public static List<DouYou> GetDouYouFromXML(XmlDocument douYouFeed)
        {
            if (douYouFeed == null) return null; //参数合法性检查

            List<DouYou> douYou = new List<DouYou>();

            //TODO: implementation

            return douYou;
        }
    }
}
